package com.yxx.utils;

import com.yxx.entityModel.dto.BiliIpInfoDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * IP地址工具类
 * @author yuxiangxun
 * @date 2025/1/18
 * @apiNote
 */
@Slf4j
public class IpUtils {
    public static String getIpSource(String ip){
        try{
            String url = "https://api.live.bilibili.com/client/v1/Ip/getInfoNew?ip={ip}";
            RestTemplate restTemplate = new RestTemplate();
            Map<String,String> paraMap = new HashMap<>(1);
            paraMap.put("ip",ip);
            // 这里拿不到city isp latitude longitude 的值？ 如果是本地运行确实是拿不到的
            BiliIpInfoDTO biliIpInfoDTO = restTemplate.getForObject(url, BiliIpInfoDTO.class, paraMap);
            log.info("查看biliIpInfoDTO:{}",biliIpInfoDTO);
            if(biliIpInfoDTO != null && biliIpInfoDTO.getCode() == 0){
                BiliIpInfoDTO.IpInfoData ipInfoData = biliIpInfoDTO.getData();
                log.info("ipInfoData:{}",ipInfoData);
                if(ipInfoData != null){
                    String ipSource = ipInfoData.getCountry() + "|" + ipInfoData.getProvince() + "|" + ipInfoData.getCity() + "|" + ipInfoData.getIsp();
                    log.info("ipSource为：{}",ipSource);
                    return ipSource;
                }
            }
        }catch (Exception e){
            log.info("getIpSource fail, e:{}",e);
            return null;
        }
        return null;
    }
}
